package com.onefinger.services;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.onefinger.aspect.Cache;
import com.onefinger.aspect.Uncache;
import com.onefinger.domain.Language;
import com.onefinger.repository.GenericRepository;

public class LanguageService implements ILanguageService {

	private static final Logger logger = LoggerFactory.getLogger(LanguageService.class);

	@Autowired
	GenericRepository<Language> genericRepository; 
	
	@Cache(cacheKey="languages", expireTime=0)
	public List<Language> list() {
		return genericRepository.getList(Language.class);
	}

	
	@Uncache(cacheKey="languages")
	public boolean save(Language language) {
		try {
			// TODO: get last version before save...
			if( language.getId() != null && language.getId() != 0 )
			{
				Language find = genericRepository.find(Language.class, language.getId() );
				language.setVersion(find.getVersion());
				language.updateVersion();
			} else {
				language.setVersion(0L);
			}
			
			genericRepository.save(language);
		} catch (Exception e) {
			logger.debug(e.getMessage());
			return false;
		}
		return true;
	}

	@Uncache(cacheKey="languages")
	public boolean remove(Language language) {
		try {
			genericRepository.remove(language);
		} catch (Exception e) {
			
			return false;
		}
		return true;
	}


	public Language find(String languageid) {
		try {
			return genericRepository.find(Language.class, "name", languageid );
		} catch (Exception e) {
			return null;
		}
	}


	@Uncache(cacheKey="languages")
	public boolean updateAllVersions() {
		List<Language> languages = list();
		for (Language language : languages) {
			language.updateVersion();
			genericRepository.save(language);
		}
		return true;
	}


	@Uncache(cacheKey="languages")
	public boolean updateVersion(String languageid) {
		Language find = find( languageid );
		if( find != null )
		{
			find.updateVersion();
			genericRepository.save(find);
			return true;
		} else {
			return false;
		}
			
	}

}
